// pages/user_centre/message/message.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    messages: [],
		loading:true
  },


  /**
   *	获取信息
   */
  getMessages() {
    const thiz = this
    wx.cloud.callFunction({
      // 要调用的云函数名称
      name: 'allMessages',
      // 传递给云函数的参数
      data: {},
      success: res => {
        // output: res.result === 3
        console.log("all Messages succ", res)
        let messages = res.result.messages
        for (let i = 0; i < messages.length; i++) {
					messages[i].date = thiz.formatMsgTime(messages[i].date)
        }
				messages.reverse()
        thiz.setData({
          messages: messages,
					loading:false
        })
      },
      fail: err => {
        // handle error
        console.log("all Messages fail", err)
      },
      complete: () => {
        // ...
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.getMessages()

		//清除已读
		getApp().globalData.unread = 0

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },


  /**
   * 传入时间戳，返回距离现在多少天
   */
  formatMsgTime: function(dateStr) {
    // var dateObj = dateStr.replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '').replace(/(-)/g, '/')
    // var targetDate = new Date(dateObj);
    var targetDate = new Date(dateStr);
    var year = targetDate.getFullYear();
    var month = targetDate.getMonth() + 1;
    var day = targetDate.getDate();
    var hour = targetDate.getHours();
    var minute = targetDate.getMinutes();
    var second = targetDate.getSeconds();
    var nowDate = new Date();
    var now_new = Date.parse(nowDate.toString());
    var milliseconds = 0;
    var timeSpanStr;
    milliseconds = now_new - targetDate;
    if (milliseconds <= 1000 * 60 * 1) {
      timeSpanStr = '刚刚';
    } else if (1000 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60) {
      timeSpanStr = Math.round((milliseconds / (1000 * 60))) + '分钟前';
    } else if (1000 * 60 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24) {
      timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60)) + '小时前';
    } else if (1000 * 60 * 60 * 24 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24 * 15) {
      timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60 * 24)) + '天前';
    } else if (milliseconds > 1000 * 60 * 60 * 24 * 15 && year == nowDate.getFullYear()) {
      timeSpanStr = month + '-' + day;
    } else {
      timeSpanStr = year + '-' + month + '-' + day;
    }
    return timeSpanStr;
  }

})